/*AyflEomXWyqCHfdTxzWda1f37E6BmbYMFlQ4qgWlYuq3WYvveC97Qm1zYJR3TbDu*/
/*
 * @Author: Chendch
 * @Date: 2020-10-13 14:38:39
 * @LastEditors: Chendch
 * @LastEditTime: 2021-11-25 14:08:11
 */
import React, {Component, Fragment} from "react";
import ReactDOM from 'react-dom';

import { ajax, toast, high, print, output, cardCache, promptBox, deepClone, pageTo } from 'nc-lightapp-front';
import draw from "./render/renderDOM";
import {initTemplate, supplierBasicFormAfterEvent, supplierBasicFormBeforeEvent, cardTableOperatEvent} from "./events";
import {constProp, statusProp, Urls, referUrls} from "./CONSTANCE";
import {queryorg, updateOrgsgrid, delOrg, querySublingCardData, freezeSupplier} from "./dataManage";
import asyncGetMainTabTableData from "./controlMethod/asyncGetMainTabTableData";
import {
  deleteFinanceOrStock, getCurCardStatus, onCardButtonClick, onCardTableButtonClick, onFinanceOrPurchaseCardButtonClick,
  onFinanceTableButtonClick, onStockTableButtonClick,saveCardInfo,beforSaveValidate,checkForm,
  querySupFinanceOrStockTableData, setCardButtonStatus, setCardStatus, setFinanceCardBtnStatus
} from './events/clickEvent/SupCardButtonAction';
import {createCustContent, onCreateCustSureBtnClick, onCreateCustCancelBtnClick, onAfterCreateCustClose} from "../utils/createCust";
import {onAssociateCustSureClick, onAssociateCustCancelBtnClick, onAssociateCustPrompSureBtnClick, associateCustContent} from "../utils/AssociateCust";
import OrgSelect from '../assign/QuickAssign'; //组织选择（分配使用）
import confirmUtil from '../../../public/pubComponent/confirmUtil/confirmUtil';
import {
  convertForm2GridData, dealRefTemplateItems,
  filterEmptyData, getCurParam, getDialogConfig, hasOperateAuth, resetTableRows, resizeForm,
  setCodeAndDeleteStatusFieldLink, setFinanceAndStockReferCondition, showAddressBookDialog,validateAddOrCopy,
  showFormulaSetting, updateFormItemDisable, updateFormItemRequire, validateFormulaSetting,beforeEdit,editSupBaseInfo
} from '../utils/SupplierUtils';
import QueryHasAssignOrg from '../component/QueryHasAssignOrg'; //已分配组织查询
import {renderContentArea} from "./render/renderTableContent";
import {onMainTableOperateDelClick} from "../utils/deleteSupplier";
import Utils from '../../../public/utils';

const {PrintOutput} = high;
const { setDefData, getDefData } = cardCache;
require("./index.less");
class SupplierBaseCard extends Component {
    constructor(props) {
        super(props);
        props.use.form('cardsupbankacc','accbasinfo','netbankinfo','queryHasAssignOrg_supplier',constProp.SUPFINANCE_CARD,constProp.SUPSTOCK_CARD,
            'createCust','associcust',constProp.SUP_BASE_CARD,'linkman', constProp.SUP_BASE_FORM, "linkmanRefer", "versionList_card", "versionCard");
        props.use.table('supplier_baseInfo');
        props.use.editTable('supaddress', 'suplinkman','supcountrytaxes','supbankacc','finance','purchase', "versionList");
        props.use.table('SubjectOrg');
        //多语对象
        this.Lang = {};
        this.inlt = null;
        //初始state
        this.state = {
            loadLang:false,
            envParam:undefined,/*初始参数*/
            indivOrg:undefined,
            billType:this.props.billType,
            createVersion:props.getUrlParam('createVersion') || false,
            version:props.getUrlParam('version'),
            begindate:props.getUrlParam('begindate'),
            isCopy:props.getUrlParam("isCopy"),
            activeTab: 0,
            activeChildTab: 0,
            showBasicTabChild: true,
            activeChildCode: "supbankacc",
            childTitleList: ["supbankacc", "suplinkman", "supcountrytaxes"],
            copyChildTitleList: ["supbankacc", "suplinkman", "supcountrytaxes"],
            status: "browse",
            disAssign: true,
            fromLinkId: this.props.getUrlParam('id'),
            fromListId:  this.props.getUrlParam('idx')
        };
        initTemplate.call(this, this.props);
    }

    modelSave = ()=>{}

    onTabChange = (mainAreaCode, code) => {
        let list = ["supplier_baseInfo_card", "finance", "purchase"],
            {childTitleList} = this.state;
        let additionState = mainAreaCode == "supplier_baseInfo_card" ?{
            showBasicTabChild: code === "supplier_baseInfo_card" ? true : false,
            currMainCode: code,
            activeTab: list.indexOf(code)
        } : {
            activeChildCode: code,
            activeChildTab: childTitleList.indexOf(code)
        };
        this.setState(additionState);
        const {props} = this;
        if(code == "supplier_baseInfo_card" || mainAreaCode !== "supplier_baseInfo_card") return ;
        let pageInfo = props.editTable.getTablePageInfo(code) || {pageIndex: 0, pageSize: "10"};
        console.log("666--", pageInfo)
        asyncGetMainTabTableData.call(this, code,  pageInfo);
    }

    setBtnVisByCode = (code) => {
        const allbtns = this.props.button.getButtons().filter( item => {
            return item.area == "header-button-area"
        }).map( item => {
            return item.key
        });
    }

    onClickPageInfo = (props, config, pks) => {
        let pageInfo = props.editTable.getTablePageInfo(this.state.currMainCode);
        asyncGetMainTabTableData.call(this, this.state.currMainCode, pageInfo);
    }

    supplierBasicFormBeforeEvent = (props, moduleId, key, value, data) => {
        supplierBasicFormBeforeEvent.call(this, props, moduleId, key, value, data);
    }

    onAfterCardFormEditEvent =(props, moduleId, key, value, index)=>{
        supplierBasicFormAfterEvent.call(this, props, moduleId, key, value, index)
    }

    cachePageInfo = (callback = ()=>{})=>{
        this.setState(this.state,callback);
    }
    /**
     * 初始页面数据
     * @param setCardValue
     * @param setCardStatus
     * @param url
     * @param isCancel
     */
    initPageData = (setCardValue,setCardStatus,url,isCancel,isCardRefresh,isDelete,isForceToInit)=>{
        let {status,dirtyRecords,envParam,card} = this.state;
        let {pagecode,nodeType,pk_supplier,directOpenCard} = this.props;

        this.cachePageInfo(() => {
            let param,
                {relateQueryId} = this.state;
            //重置列宽
            resizeForm.call(this,constProp.SUP_BASE_CARD);
            param = relateQueryId && status!='add'? {pk_supplier:[relateQueryId]}: getCurParam.call(this,'pk_supplier',!!isCancel?dirtyRecords:null);
            let realUrl = Urls.addUrl;
            if(url) {
                realUrl = url;
            }else if(param && !!param['pk_supplier'][0]) {
                realUrl = Urls.queryCardUrl;
            }
            ajax({
                url: realUrl,
                data:{
                    pk_supplier:param ? param['pk_supplier'][0]:null,
                    tsMap:param?param['tsMap']:null,
                    pageCode:pagecode,
                    nodeType:nodeType,
                    pk_curOrg:envParam.pk_org,
                    status:status,//！！！新增取消时回滚单据号
                },
                success:(res)=>{
                    if(res.data){
                        var tables = new Object();
                        this.state.card.table.tableIds.forEach(tableId=>{
                            tables[tableId] = 'editTable';
                        })
                        //显示公式设置
                        showFormulaSetting.call(this,res,{
                            [card.form.formId]:'form',
                            ...tables
                        })

                        res.success && setCardValue && setCardValue({data:res.data,isCardRefresh,isDelete, isForceToInit},setCardStatus);
                        if(this.state.version){
                            this.props.form.setFormItemsValue(constProp.SUP_BASE_CARD, {'version': {value:`${this.state.version}`,disaply:`${this.state.version}`}});
                        }
                        if(this.state.begindate){
                            this.props.form.setFormItemsValue(constProp.SUP_BASE_CARD, {'begindate': {value:this.state.begindate,disaply:this.state.begindate}});
                        }
                        let isCopy=this.state.isCopy;
                        if (isCopy) {
                            this.props.form.setFormItemsValue(constProp.SUP_BASE_CARD, {'version': {value:`${1}`,disaply:`${1}`}});
                            this.props.form.setFormItemsValue(constProp.SUP_BASE_CARD, {'begindate': {value:"1970-01-01 00:00:00",disaply:"1970-01-01"}});
                            this.props.form.setFormItemsValue(constProp.SUP_BASE_CARD, {'pk_supplier_v': {value:"",disaply:""}});
                            this.state.isCopy = false;
                        }
                        directOpenCard && pk_supplier && this.resetCurPageNodeTypeWhenDirectOpenCard(res.data)
                        this.copy_pk_supplier =  res.data.copy_pk_supplier || null;
                        if(!!this.copy_pk_supplier){
                            this.props.editTable.setTableData("suplinkman", {rows:[]});
                        }
                    }else{
                        toast({title:this.Lang['10140SUG-000261'],color:'warning'});/* 国际化处理：数据已被删除，或者被修改，请返回列表刷新数据！*/
                    }

                }
            })
        });
    }

    /**
     * 批改完成事件
     * @param callback
     * update by yufwm 2020-03-17 url 编写错误 修改
     */
    onBatchUpdateFinish = (callback = ()=>{})=>{
        let me = this;
        debugger
        let param = me.BatchUpdateComp.getBatchUpdateData();
        !!param && ajax({
            url:Urls.quickBatchUpdateUrl,
            data:param,
            success:(res)=>{
                let {data} = res;
                let {errorLogResult} = data;
                let {errorMessagegNum, errorMsgs} = errorLogResult;
                if (errorMessagegNum !== '0') {
                    toast({color: 'warning', content: errorMsgs.map(item => item.errormsg).join(";")});
                } else {
                //批改后刷新表单或表格
                me.initPageData(me.setCardValue,me.setCardStatus);
                //批改后清空批改信息
                me.BatchUpdateComp.cleanBatchUpdateData();
                //批改后关闭批改弹窗
                callback && callback();
                res.success && toast({title:this.Lang['10140SUG-000161'],color:'success'});/* 国际化处理： 批改成功！,批改成功*/
                }
            }
        })
    }
    /**
     * 批改弹出框取消事件
     */
    onBatchUpdateCancelClick = (callback)=>{
        this.BatchUpdateComp.cleanBatchUpdateData(callback);
    }
    /**
     * 供应商联系人表格编辑前事件
     */
    onSupLinkmanTableBeforeEdit = (props, moduleId, key, value,  index, record,status)=>{
        //只有'是否默认'字段 允许编辑
        return key.attrcode == 'isdefault';
    }

     /**
     * 联系人dialog关闭后事件
     */
    onLinkmanDialogClose = (callback)=>{
        let {formId,targetId} = this.state.dialog.linkman;
        if(!this.props.form.isCheckNow(formId)){
            return;
        }

        let formData = this.props.form.getAllFormValue(formId);
        // 根据平台返回的状态判定是新增还是修正
        let linkEditStatus = formData.rows[0].status
        let isAdd = linkEditStatus == 2
        formData.areacode = formId;//添加表单的areacode编码
        formData.rows['status'] = '2';//设置状态
        var data = {
            model: formData,
            pageid: pageTo.getPageCode(),
        };
        //验证公式
        validateFormulaSetting.call(this,data,()=>{
            ajax({
                url: Urls.saveLinkmanUrl,
                data: data,
                success:(res)=>{
                    callback && callback();//关闭弹窗
                    this.setState({openDialog:false},()=>{
                        let rowNumber = this.props.editTable.getNumberOfRows(targetId);
                        //1 更新 2 新增
                        !isAdd?
                            resetTableRows.call(this,targetId, false, convertForm2GridData.call(this,res.data["suplinkman"].rows[0].values,targetId, true)):
                            this.props.editTable.addRow(targetId, rowNumber, false, convertForm2GridData.call(this,res.data["suplinkman"].rows[0].values,targetId, true));
                        this.props.editTable.setStatus(targetId,'edit');
                    });
                }
            });
        },{[formId]:'form'},'form');
    }

    /**
     * dialog关闭后事件
     */
    onAfterDialogClose = (callback)=>{
        this.setState({openDialog:false},callback);
    }
    /**
     * 卡片form按钮事件
     * @param props
     * @param id
     */
    onCardButtonClick = (props,id)=>{
        onCardButtonClick.call(this,props,id)
    }

    /**
         * 冻结解冻业务单元选择
         * @param value
     */
    onBusinessUnitChange = (value)=>{
        this.state.freezeOrgParam.value = value;
        this.setState(this.state);
    }

    /**
     * 卡片分页导航事件
     */
    handleCardPagination = async(props,pk)=>{
        if(!pk){return;}
        this.props.cardPagination.setCardPaginationId({id:pk,status:1})
        const data = await querySublingCardData.call(this, pk);
        if(data === "error") return ;
        this.setState({
            relateQueryId: pk,
            selectedRecords:[data.head[constProp.SUP_BASE_CARD].rows[0].values],
            dirtyRecords:[data.head[constProp.SUP_BASE_CARD].rows[0].values]},()=>{
            this.setCardValue({data:data},()=>{
                //回调 表单表格设置状态
                this.setCardStatus({status:'browse'},setCardButtonStatus);
            });
        })
    }

    /* ↓↓↓↓↓↓↓=================================================================联系人组织权限处理逻辑===========================================================↓↓↓↓↓↓↓↓↓*/

    assignOrg= async (phone)=>{
        let { ncmodal } = this.props;
        let {show } = ncmodal;
        const data = await queryorg.call(this, phone);
        if(data == "error") return ;
        this.setState({
            leftTree:data.leftTree,
            rightTree:data.rightTree,
            curPhone:phone
        },() => {
            show('SubjectOrgModal');
        })
    }

    /**
     * 刷新组织权限
     */
    refreshOrg = async ()=>{
        let phone = this.props.form.getFormItemsValue("linkman",'cell').value;
        const data = await updateOrgsgrid.call(this, phone);
        if(data == "error") return ;
        this.props.table.setAllTableData("SubjectOrg",{rows: Object.keys(data).length ? data.SubjectOrg.rows : []});
    }

    /*
     *  选中模式
     */
    handleChange(value) {
        this.setState({
            selectType: value
        });
    }

    /**
     * 删除移动用户的组织权限
     */
    deletePromptBox = (org)=>{
        promptBox({
            color: 'warning',
            title: this.Lang['10140SUG-000071'],/* 国际化处理： 确认删除*/
            content: this.Lang['10140SUG-000072'],/* 国际化处理： 您确认要删除所选数据么？*/
            beSureBtnClick: () => {this.deleteOrg(org)}
        });
    }

    /**
     * 删除移动用户的组织权限
     */
    deleteOrg = async (org)=>{
        let phone = this.props.form.getFormItemsValue("linkman",'cell').value;
        const data = await delOrg.call(this, {phone, org});
        if(data == "error") return ;
        this.refreshOrg();
    }

    /**
         * 已分配组织查询内容区
         * @returns {*}
        */
    queryHasAssignOrgContent = ()=>{
        return (<QueryHasAssignOrg {...Object.assign(this.props,{selectedRecords:this.state.selectedRecords},{Lang:this.Lang,inlt:this.inlt})} ref={(HasAssignOrg)=>{this.HasAssignOrg = HasAssignOrg;}}/>)
    }

    /**
     * 冻结解冻弹出框 内容
     * @returns {*}
     * update by yufwm 2020-03-13 给 BusiUnitRefer参照添加 固定宽度
     */
    freezeOrgSelect = ()=>{
        let {freezeOrgParam} = this.state,{BusiUnitRefer} =referUrls;
        return(
            <div className="sup-freeze-div" style={{display: 'flex'}}>
                <div style={{display: 'flex',alignItems: 'center'}}>
                    <div className="ncc-hr-font" style={{marginRight: 10,width: 150,'text-align':'right'}}>{this.Lang['10140SUG-000130']}</div>
                </div>
                <div style={{display: 'flex',alignItems: 'center',width:'300px'}}>
                    {window[BusiUnitRefer].default({...freezeOrgParam})}
                    {/* <BusinessUnitTreeRef {...this.state.freezeOrgParam}/> */}
                </div>
            </div>
        );
    }

    /**
         * 添加卡片子表肩部按钮
         * @param key
         * @returns {*}
     */
    addCardTableButton = (key)=>{
        let { createButtonApp} = this.props.button;
        return ( <div className="shoulder-definition-area" fieldid="suplinkman_table-area">
            <div className="definition-icons" fieldid="tabs-area">
                {this.state.card.table[key].btnApp && createButtonApp(this.state.card.table[key].btnApp)}
            </div>
        </div>);
    }

    /**
        * 表格行双击事件
        * @param moduleId
        * @param props
        * @param record
        * @param index
    */
    onRowDoubleClick = (moduleId,status,record, index, props)=>{
        if(this.state.status == 'add' || this.state.status == 'edit'){
            //卡片编辑态，聚合关系子表不能操作
            return;
        }
        this.setState({dblClkRecord:record},()=>{
        let param = {
            dialogTitle:moduleId == constProp.FINANCE?this.Lang['10140SUG-000112']:this.Lang['10140SUG-000113'],/* 国际化处理： 财务信息,采购信息*/
            dialogWidth:'50%',
            dialogHeight:'60%',
            dialogZIndex:'100',
            showFooter:false,//显示底部按钮区
            showDefaultBtn:false,//显示默认按钮
            listener:{
                renderContentArea:renderContentArea.bind(this,moduleId),
                onAfterShow:
                    moduleId==constProp.FINANCE?
                    this.onFinanceDialogAfterShow.bind(this,setFinanceCardBtnStatus.bind(this),null,status?status:statusProp.BROWSE):
                    this.onStockDialogAfterShow.bind(this,setFinanceCardBtnStatus.bind(this),null,status?status:statusProp.BROWSE),
                onBeforeCancelClick:(callback)=>{querySupFinanceOrStockTableData.call(this,moduleId,true);callback && callback();},
                onAfterCancelClick:this.onAfterDialogClose,
            }
        };
        setFinanceAndStockReferCondition.call(this,moduleId==constProp.FINANCE?'supfinance_card':'supstock_card',record.hasOwnProperty('data')?record.data.values:record.values);
        this.setState({openDialog:true},()=>{
            this.Dialog.showDialog(Object.assign(param,{Lang:this.Lang}));
        })
        });
    }
    onFinanceOrPurchaseTableSelected = (tableId,props, moduleId, record, index, status)=>{
        this.setFinanceOrPurchaseTableButton(tableId);
    }
    onFinanceOrPurchaseTableSelectedAll = (tableId,props, moduleId, status, length)=>{
        this.setFinanceOrPurchaseTableButton(tableId);
    }
    setFinanceOrPurchaseTableButton = (tableId)=>{
        let selectedRecords = this.props.editTable.getCheckedRows(tableId);
        // let flag = tableId =='finance'?(selectedRecords.length>1?false:(selectedRecords[0].data.values['payfreezeflag'].value == true ? true:false)):true;
        this.props.button.setButtonDisabled({
            Finance_Table_Print:!(tableId == 'finance' && selectedRecords && selectedRecords.length>0),
            Finance_Table_Output:!(tableId == 'finance' && selectedRecords && selectedRecords.length>0),
            Finance_Table_Delete:!(tableId == 'finance' && selectedRecords && selectedRecords.length>0),
            Finance_Table_PayFreeze:tableId =='finance'?(selectedRecords.length>1?false:(selectedRecords[0] ? (selectedRecords[0].data.values['payfreezeflag'].value == true ? true:false):true)):true,
            Finance_Table_PayUnFreeze:tableId =='finance'?(selectedRecords.length>1?false:(selectedRecords[0] && selectedRecords[0].data.values['payfreezeflag'].value == true?false:true)):true,
            Finance_Table_TicketFreeze:tableId =='finance'?(selectedRecords.length>1?false:(selectedRecords[0] ? (selectedRecords[0].data.values['makeoutfreezeflag'].value == true ? true:false):true)):true,
            Finance_Table_TicketUnFreeze:tableId =='finance'?(selectedRecords.length>1?false:(selectedRecords[0] && selectedRecords[0].data.values['makeoutfreezeflag'].value == true?false:true)):true,
            Stock_Table_Delete:!(tableId == 'purchase' && selectedRecords && selectedRecords.length>0),
            Stock_Table_OrderFreeze:tableId =='purchase'?(selectedRecords.length>1?false:(selectedRecords[0] ? (selectedRecords[0].data.values['orderfreezeflag'].value == true ? true:false):true)):true,
            Stock_Table_OrderUnFreeze:tableId =='purchase'?(selectedRecords.length>1?false:(selectedRecords[0] && selectedRecords[0].data.values['orderfreezeflag'].value == true?false:true)):true,
            Stock_Table_Print:!(tableId == 'purchase' && selectedRecords && selectedRecords.length>0),
            Stock_Table_Output:!(tableId == 'purchase' && selectedRecords && selectedRecords.length>0),
        });
    }

    /**
     * 由于业务单元节点  向导批改带有查询组织 向导分配不带查询组织，所以这里做一下适配
     */
    setOrgAssignToCache = ()=>{
        if(this.props.nodeType == 'ORG_NODE'){
        let assignSearchItems = this.props.meta.getMeta()['assignsupplierquery'].items;
        if(assignSearchItems[0].attrcode == 'pk_org_assign'){
            this.state.orgAssignCacheField = assignSearchItems[0];
            assignSearchItems.splice(0,1);
            this.setState(this.state,()=>{
            this.props.meta.setMeta(this.props.meta.getMeta());
            });
        }
        }
    }
    componentDidUpdate(){
        //编辑态关闭浏览器页签 提示
        if(this.state.status == 'edit' ||this.state.status == 'add'){
            window.onbeforeunload = () => {
                return '';
            };
        }else{
            window.onbeforeunload = null;
        }
    }

    /**
         * 自定义表格field适配
         * @param metaId
     */
    meta2TableFieldAdapter = (metaId)=>{
        this.props.meta.getMeta()[metaId].items.forEach(item=>{
            item.title = item.label;
            item.dataIndex = item.attrcode;
            item.key = item.attrcode;
            item.width = 100;
        })
    }

     /**
     * 设置停启用按钮的禁用状态
     * @param flag
     */
    disabledEnableButtons = (flag)=>{
        if(flag=='cancel'){
            this.props.button.setButtonDisabled({Disable:false,Enable:false});
        }else{
            this.props.button.setButtonDisabled({Disable:!flag,Enable:!!flag});
        }
    }
    /**
     * 是否禁用核准按钮
     * @param flag
     */
    disabledApproveButtons = (flag)=>{
        if(flag=='cancel'){
            this.props.button.setButtonDisabled({UnApprove:false,Approve:false});

        }else{
            this.props.button.setButtonDisabled({UnApprove:!flag,Approve:!!flag});
        }
    }
    displayEnablestate = (flag)=>{
        let {selectedRecords} = this.state;
        let record = selectedRecords[0].values?selectedRecords[0].values:selectedRecords[0];
        let data = record.data?record.data.values:record;
        this.props.button.setButtonVisible({
            Card_Enable:!!data['pk_supplier'].value?!flag:false,
            Card_Disable:!!data['pk_supplier'].value?flag:false
        });
    }

    displayApproveButtons = (flag,addCancel) =>{
        let {selectedRecords} = this.state;
        let record = selectedRecords[0].values?selectedRecords[0].values:selectedRecords[0];
        let data = record.data?record.data.values:record;
        this.props.button.setButtonVisible({
            Card_Approve:!!data['pk_supplier'].value?!flag:false,
            Card_UnApprove:!!data['pk_supplier'].value?flag:false
        });
    }

    //多版本校验编码编辑性
    checkCodeEdit = (status) => {
        return new Promise( (resolve, reject) => {
            if(["add", "edit"].includes(status)) {
                ajax({
                    url: "/nccloud/uapbd/supplier/supplierCodeCanEdit.do",
                    data:{
                        pk_org:this.props.form.getAllFormValue(constProp.SUP_BASE_FORM).rows[0].values.pk_org.value,
                    },
                    success:(res)=>{
                        if(typeof res.data != "undefined"){
                            resolve(res.data);
                        }else {
                            resolve(undefined);
                        }
                    }
                })
            }else {
                resolve(undefined);
            }
        })
    }

    /**
     * 设置卡片数据
     * @param data
     * @param callback 预留的回调
    */
    setCardValue = async ({data = {},isCardRefresh,isDelete, isForceToInit} = {},callback=()=>{})=>{
        let {status,card} = this.state,
            {nodeType} = this.props,
            cardData = data.hasOwnProperty("card") ? data.card : data,
            formvalues = cardData.head[card.form.formId].rows[0].values || [],
            formData = filterEmptyData(formvalues,status);
        cardData && this.props.form.setAllFormValue({[card.form.formId]:formData});
        cardData && this.props.form.setAllFormValue({[card.form.baseFormId]:formData});
        if(!!this.props.getUrlParam("isCopy")) {
            this.props.form.setFormItemsValue([card.form.formId],
                {pk_supplier: {value: null, display: null},iscustomer: {value: false, display: null}, corcustomer: {value: null, display: null}}
            );
        }
        //设置表格数据
        setTimeout(card.table.tableIds.forEach((key)=>{
            this.props.editTable.setTableData(card.table[key].tableId, cardData.bodys[key]?{rows:cardData.bodys[key].rows}:{rows:[]});
        }),0);
        let pkOrgValue = cardData.head.supplier_baseInfo_card.rows[0].values.pk_org.value,
            innerprofitcenterValue = cardData.head.supplier_baseInfo_card.rows[0].values.innerprofitcenter.value;
        //业务单元会禁用及清空供应商类型、内部利润中心、对应财务组织、对应利润中心字段
        let disabledVO = {
            code:cardData.head.userjson == 'Y',
            supprop: "ORG_NODE" == nodeType && pkOrgValue ? true:false, //供应商类型
            innerprofitcenter: "ORG_NODE" == nodeType && pkOrgValue ? true : false,//内部利润中心
            pk_financeorg: "ORG_NODE" == nodeType && pkOrgValue ? true : false,//对应财务组织
            pk_profitcenter: "ORG_NODE" == nodeType && pkOrgValue ? true : false//对应利润中心
        };


        //集团、全局初始化根据利润中心禁用
        ["GLOBE_NODE", "GROUP_NODE"].includes(nodeType) && Object.assign(disabledVO, {
            pk_profitcenter: !innerprofitcenterValue
        })

        "ORG_NODE" == nodeType && pkOrgValue && this.props.form.setFormItemsValue("supplier_baseInfo_card",{
                innerprofitcenter: {value: false},//内部利润中心
                pk_financeorg: {value:'',display:''},//对应财务组织
                pk_profitcenter: {value:'',display:''},//对应利润中心
            });

        let codeEdit = await this.checkCodeEdit(status);
        if(typeof codeEdit != "undefined") {
            disabledVO.code = !codeEdit;
        }
        this.props.form.setFormItemsDisabled(constProp.SUP_BASE_FORM, {
            code: disabledVO.code
        });
        //根据编码规则定义 设置code是否可编辑
        updateFormItemDisable.call(this,{
            areaId: constProp.SUP_BASE_CARD,
            data: disabledVO
        },()=>{
            // //没有财务和采购信息时 隐藏按钮
            this.setState({
                selectedRecords:[cardData.head[card.form.formId].rows[0].values],
                disAssign: !this.props.form.getFormItemsValue("supplier_baseInfo_card", "ismobilecoopertive").value
            },()=>{
                //回调 表单表格设置状态
                callback({status,isCardRefresh,isDelete, isForceToInit},setCardButtonStatus);
            });
        });
    }

  /**
   * 设置卡片状态
   * @param status
   * @param callback
   */
  setCardStatus =({status,isCardRefresh,isDelete, isForceToInit} = {},callback)=>{
    let curStatus = getCurCardStatus(status);
    //设置表单编辑态
    this.props.form.setFormStatus(this.state.card.form.formId, curStatus);
    this.props.form.setFormStatus(this.state.card.form.baseFormId, curStatus);
    this.setInitTabbyStatus(curStatus == "browse", isForceToInit);
    //聚合关系的表格编辑态
    this.state.card.table.tableIds.forEach((key)=>{
        this.state.card.table[key].relate == 'agg' && this.props.editTable.setStatus(this.state.card.table[key].tableId,curStatus);
    })
    !isDelete && (callback ? callback.call(this):setCardButtonStatus.call(this));//设置卡片按钮状态
    isCardRefresh && toast({title:this.Lang['10140SUG-000200'],color:'success'})/* 国际化处理： 刷新成功！*/
    this.setState(this.state,()=>{
        let formData = this.props.form.getAllFormValue(this.state.card.form.formId);
        var supstateFlag = formData.rows[0].values['supprop'].value =='1'
        var supstateName = formData.rows[0].values['supprop'].display != '';
        updateFormItemDisable.call(this,{
            areaId:constProp.SUP_BASE_CARD,
            data:{'pk_financeorg': !supstateFlag}
        },()=>{
            updateFormItemRequire.call(this,{
                areaId:constProp.SUP_BASE_CARD,
                data:{'pk_financeorg':supstateName && supstateFlag}
            },()=>{
                !!formData.rows[0].values['code'].value && !supstateFlag && this.props.form.setFormItemsValue(constProp.SUP_BASE_CARD,{'pk_financeorg':{display:'',value:''}});
            })
        });
        // this.props.form.setFormItemsDisabled(constProp.SUP_BASE_CARD,{'pk_financeorg':supstateName && !supstateFlag});
        // this.props.form.setFormItemsRequired(constProp.SUP_BASE_CARD,{'pk_financeorg':supstateName && supstateFlag});
        // !supstateFlag && this.props.form.setFormItemsValue(constProp.SUP_BASE_CARD,{'pk_financeorg':{display:'',value:''}});
    })
  }

    /**
     * 分配 内容
     * @returns {*}
     */
    assignContent = ()=>{
        return(<OrgSelect {...Object.assign(this.props,{Lang:this.Lang,inlt:this.inlt})} ref={( item )=> this.orgSelect = item}/>)
    }

     /**
     * 供应商分配确定前事件
     * @param callback
     */
    onSupFastAssignBeforeSureClick = (callback)=>{
        this.assignSupplier(true,callback);
    }
    /**
     * 供应商取消分配确定前事件
     * @param callback
     */
    onSupFastCancelAssignBeforeSureClick = (callback)=>{
        this.assignSupplier(false,callback);
    }

    /**
     * 分配供应商
     * @param assign
     * @param callback
     */
    assignSupplier = (assign,callback)=>{
        let targetOrgs = this.orgSelect.getData();
        let param = getCurParam.call(this,'pk_supplier');
        targetOrgs?ajax({
            url:assign?Urls.assignUrl:Urls.cancelAssignUrl,
            data:Object.assign(param,{targetIds:targetOrgs},{isFastAssign:true}),
            success:(res)=>{
                this.orgSelect.clearData();//清空分配的数据
                this.initPageData(this.setCardValue,this.setCardStatus);
                res.success && toast({content:assign?this.Lang['10140SUG-000023']:this.Lang['10140SUG-000133'],color:'success'});/* 国际化处理： 分配成功！,取消分配成功！*/
                res.success && callback && callback(res);
            }
        }):toast({content:this.Lang['10140SUG-000134'],color:'warning'});/* 国际化处理： 没有指定操作的目标组织！*/
    }

    setInitTabbyStatus = (type = true, isForceToInit = false) => {//true表示浏览态 isForceToInit用于强制切换回首页签(例如批量批改操作)
        let {tabList, tabChildList, rawTabList, rawTabChildList, copyChildTitleList} = this.state;
        tabList = type ? deepClone(rawTabList) : rawTabList.slice(0, 1);
        tabChildList = type ? deepClone(rawTabChildList) : rawTabChildList.slice(1, rawTabChildList.length);
        let additionState = type ? {activeChildCode: "supbankacc", activeChildTab: 0} : {activeChildCode: "suplinkman", activeChildTab: 0},
            childTitleList = type ? copyChildTitleList : copyChildTitleList.slice(1, copyChildTitleList.length);
        Object.assign(this.state, {
            tabList,
            childTitleList,
            tabChildList,
            showBasicTabChild: true,
            activeTab: 0,
            currMainCode: "supplier_baseInfo_card",
            ...additionState
        });
    }

     /**
     * 卡片子表编辑或删除操作按钮事件
     * @param key
     * @param text
     * @param record
     * @param index
     */
    onCardTableOperatEvent = (key,flag,text,record,index)=>{
        cardTableOperatEvent.call(this, key,flag,text,record,index);
    }

     /**
     * 生成客户弹窗内容
     */
    createCustContent = ()=>{
        return createCustContent.call(this);
    }
    /**
     * 生成客户确认按钮点击前 事件
     */
    onCreateCustSureBtnClick = (callback,destroyHotKeys)=>{
        onCreateCustSureBtnClick.call(this, callback, destroyHotKeys);
    }
    /**
     * 生成客户取消按钮点击事件
     * @param callback
     */
    onCreateCustCancelBtnClick = (callback,destroyHotKeys)=>{
        onCreateCustCancelBtnClick.call(this, callback, destroyHotKeys);
    }
    /**
     * 生成客户弹窗关闭后事件
     */
    onAfterCreateCustClose = ()=>{
        onAfterCreateCustClose.call(this);
    }

   /**
     * 创建 关联客户内容
     * @returns {*}
     */
    associateCustContent = ()=>{
        return associateCustContent.call(this);
    }
    /**
     * 关联客户确认按钮点击事件
     */
    onAssociateCustSureClick = (callback,destroyHotKeys)=>{
        onAssociateCustSureClick.call(this, callback, destroyHotKeys);
    }
    /**
     *  关联客户取消按钮 点击事件
     */
    onAssociateCustCancelBtnClick = (callback,destroyHotKeys)=>{
        onAssociateCustCancelBtnClick.call(this, callback, destroyHotKeys);
    }
    /**
     * 关联客户确认时 提示框中确认按钮点击事件
     */
    onAssociateCustPrompSureBtnClick = (callback,destroyHotKeys)=>{
        onAssociateCustPrompSureBtnClick.call(this, callback, destroyHotKeys);
    }

    /**
     * 财务信息打开弹出框后事件
     */
    onFinanceDialogAfterShow = (setBtnStatus,callback,status,isRefresh)=>{
        setBtnStatus && setBtnStatus.call(this,status);//设置按钮状态
        let formId = constProp.SUPFINANCE_CARD;
        let supParam = getCurParam.call(this,constProp.PK_SUPPLIER);
        let finParam = getCurParam.call(this,constProp.PK_SUPFINANCE,this.state.dblClkRecord);
        ajax({
            url:Urls.queryFinanceInfoUrl,
            data:{pk_supplier:supParam[constProp.PK_SUPPLIER][0],pk_supfinance:finParam[constProp.PK_SUPFINANCE][0]},
            success:(res)=>{
                showFormulaSetting.call(this,res,{[formId]:'form'});
                res.success && this.props.form.setAllFormValue({[formId]:res.data?res.data[formId]:{rows:[]}});
                //有回调执行回调，没有回调执行setCardStatus
                (callback && typeof callback==='function') ? callback.call(this,formId,status): setCardStatus.call(this,formId,status);
                isRefresh && toast({title:this.Lang['10140SUG-000200'],color:'success'})/* 国际化处理： 刷新成功！*/
            }
        })
    }
    /**
     * 采购信息打开弹出框后事件
     * @param setBtnStatus
     */
    onStockDialogAfterShow = (setBtnStatus,callback,status,isRefresh)=>{
        setBtnStatus && setBtnStatus.call(this,status);//设置按钮状态
        let param = getCurParam.call(this,constProp.PK_SUPPLIER);//获得请求参数
        let supstock = getCurParam.call(this,constProp.PK_SUPSTOCK,this.state.dblClkRecord);
        ajax({
            url:Urls.queryStockInfoUrl,
            data:{pk_supplier:param[constProp.PK_SUPPLIER][0],pk_supstock:supstock[constProp.PK_SUPSTOCK][0],nodeType:this.props.nodeType},
            success:(res)=>{
                showFormulaSetting.call(this,res,{[constProp.SUPSTOCK_CARD]:'form'});
                res.success && this.props.form.setAllFormValue({[constProp.SUPSTOCK_CARD]:res.data?res.data[constProp.SUPSTOCK_CARD]:{rows:[]}});
                (callback && typeof callback==='function') ? callback.call(this,constProp.SUPSTOCK_CARD,status): setCardStatus.call(this,constProp.SUPSTOCK_CARD,status);
                isRefresh && toast({title:this.Lang['10140SUG-000200'],color:'success'})/* 国际化处理： 刷新成功！*/
            }
        })
    }

     /**
     * 执行打印
     * @param url
     * @param nodeKey
     * @param pks
     */
    executePrint = ({isPrint,url,nodeKey,pks,isMainPrint}={})=>{
        !!isPrint?
        print(
            'pdf',
            url,
            {
                funcode:pageTo.getAppCode(),
                appcode:pageTo.getAppCode(),
                nodekey:nodeKey,
                oids:pks
        })
        :
        output(
            {
                data:{
                    funcode:pageTo.getAppCode(),
                    nodekey:nodeKey,
                    oids: pks,
                    outputType: "output"
            },
            url: url
        });
    }

    /**
     * 冻结解冻窗口关闭回调事件
     */
    onFreezeDialogClose = async (callback)=>{
        let param = getCurParam.call(this,'pk_supplier');
        let orgs = (this.state.freezeOrgParam && this.state.freezeOrgParam.value && this.state.freezeOrgParam.value.length>0)?this.state.freezeOrgParam.value.map(org=>{
            return org.refpk;
        }):[];

        const data = Object.assign(
            param,
            {freezeOrgs:orgs},
            {freeze:this.state.otherParam.freeze},
            {nodeType:this.props.nodeType,pk_curOrg:this.state.envParam.pk_org});
        const resDa = await freezeSupplier.call(this, data);
        if(resDa == "error") return ;

        this.state.freezeOrgParam.value = {};
        this.setState(this.state,()=>{
            //回调中关闭窗口
            callback && callback();
            toast({title:this.state.otherParam.freeze?this.Lang['10140SUG-000150']:this.Lang['10140SUG-000151'],color:'success'});/* 国际化处理： 冻结成功！,解冻成功！*/
        })
    }

    /***************************************common area******************************************/
    /**
     * 渲染输出组件
     */
    drawOutputComp = ()=>{
        return(
            <PrintOutput
                ref='printOutput'
                url={this.state.printUrl}
                data={{
                    funcode:pageTo.getAppCode(),//应用的appcode
                    nodekey:this.state.printNodeKey,  //需要与数据库保持一致
                    oids: this.state.printPks,//打印的数据主键集合
                    outputType: "output"
                }}
            >
            </PrintOutput>
        )
    }

    /**
     * 银行账户双击
     * **/
    supbankaccDoubleClick = (moduleId,status,record, index, props) => {
        if(status != "browse") return ;
        const virRecord = {};
        for(let [k,v] of Object.entries(record.values)) {
            virRecord[k] = v.value;
        };
        onCardButtonClick.call(this, this.props, "Card_BankAccount", () => {
            this.SupBankAcc.onRowDoubleClick(virRecord, index, window.event)
        });
    }

     /**
     * 添加卡片子表操作列
     */
    addCardTableOperateField =()=>{
        let meta = this.props.meta.getMeta();//获得元数据
        //迭代为元数据添加操作列
        const {copyChildTitleList = [], card} = this.state;
        if(!card) return null;
        Object.keys(card.table).filter(tid => copyChildTitleList.includes(tid)).forEach((key)=>{
            card.table[key].field && meta[key] && meta[key].hasOwnProperty('items') && !meta[key].items.find((item)=>item.attrcode=='opr')
                && meta[key].items.push(card.table[key].field);
        });
    }

    onMainTableOperateDelClick = (isAsyncDel) => {
        onMainTableOperateDelClick.call(this, isAsyncDel);
    }

    canCreateVersion=()=>{
        let _this = this;
        validateAddOrCopy.call(this,()=>{
            ajax({
                url: '/nccloud/uapbd/supplier/supplierCanCreateVersion.do',
                data: {pk_supplier:_this.props.form.getAllFormValue('supplier_baseInfo_card').rows[0].values['pk_supplier'].value},
                async: false,
                success: (result) => {

                    confirmUtil.call(this, {
                        title: this.Lang['10140SUG-000077'], /* 国际化处理： 询问*/
                        content: this.Lang['10140SUG-000249'],//"创建新版本后，当前版本将变为历史版本且不可修改、删除。是否创建新版本？"
                        beSureBtnClick: () => {
                            _this.props.modal.close('createVersion');
                            _this.saveVersionInfo();
                        }
                    })
                },
                error: (msg) => {
                    _this.props.modal.close('createVersion');
                    toast({ content: msg.message, color: 'danger' });
                }
            });
         })

    }

    saveVersionInfo = () => {
        let version= this.props.form.getAllFormValue("versionList_card").rows[0].values.version.value+"";
        let begindate=this.props.form.getAllFormValue("versionList_card").rows[0].values.begindate.value;
        this.setState({createVersion:true,version:version,begindate:begindate}, () =>{
            this.props.modal.close('createVersion');

            let ismobilecoopertive = this.props.form.getAllFormValue('supplier_baseInfo_card').rows[0].values['ismobilecoopertive'].value;
            if (ismobilecoopertive) {
               // this.props.form.setFormItemsRequired('suplinkman', { 'pk_linkman.cell': true });
                this.props.form.setFormItemsRequired('linkman', { 'cell': true });
            } else {
                //this.props.form.setFormItemsRequired('suplinkman', { 'pk_linkman.cell': false });
                this.props.form.setFormItemsRequired('linkman', { 'cell': false });
            }
            let formData = this.props.form.getAllFormValue(this.state.card.form.formId);
            formData.rows[0].values.begindate.value=begindate;
            formData.rows[0].values.version.value=version;
            this.props.form.setFormItemsValue(this.state.card.form.formId,{
                version:{value:version,display:version},
                begindate: {value: begindate,disaply:begindate}
            });

            saveCardInfo.call(this,checkForm,editSupBaseInfo,formData,false,() =>{
                toast({ color: 'success', title: this.Lang['10140SUG-000250'] });/* 国际化处理： 版本化成功！*/;
                beforeEdit.call(this,{
                    status:'edit',
                    selectedRecords:[this.props.form.getAllFormValue('supplier_baseInfo_card').rows[0].values],
                    dirtyRecords:[this.props.form.getAllFormValue('supplier_baseInfo_card').rows[0].values]
                },editSupBaseInfo.bind(this));
            })


        });
    }

    render() {
        return (
        <Fragment>
            {draw.call(this)}
        </Fragment>
        )
    }
}

export default SupplierBaseCard;
/*AyflEomXWyqCHfdTxzWda1f37E6BmbYMFlQ4qgWlYuq3WYvveC97Qm1zYJR3TbDu*/
